#!/usr/bin/python
# -*- coding: utf-8 -*- 
import os,sys,getopt,re

def func(spec_dir,ignore_dir,spec_word,spec_type):
    sys_file=[];
    #得到指定文件夹下所有文件位置
    for current_path, current_dirs, current_files in os.walk(spec_dir):
        for file in current_files:
            sys_file.append(current_path + "/" + file);
    len_sys_file = len(sys_file);
    #删除忽略文件夹
    key_count = [];
    for ignore_dir_str in ignore_dir:
        for i in range(len_sys_file):
            if re.search('.*'+ ignore_dir_str+ '/.*',sys_file[i]):
                key_count.append(i);
    key_count=list(set(key_count));
    key_count.reverse();

    for key in key_count:
        del sys_file[key];


    #提取指定文件
    sys_file_real=[];
    if spec_type:
        key_cont = [];
        len_sys_file = len(sys_file);
        for spec_type_str in spec_type:
            for i in range(len_sys_file):
                if re.search('.*'+ spec_type_str+ '$',sys_file[i]):
                    key_cont.append(i);
        sys_file_type=[];
        for key in key_cont:
            sys_file_real.append(sys_file[key]);
    else:
        sys_file_real = sys_file;

    return sys_file_real;

def find_word(spec_dir,ignore_dir,spec_word,spec_type):
    sys_file_arr = func(spec_dir,ignore_dir,spec_word,spec_type)
    
    print "*"*70;
    
    #遍历返回文件元组查找指定单词
    for sys_file_str in sys_file_arr:    
        file=open(sys_file_str);
        linen=1;
        line=file.readline()
        while line:
            search =spec_word;
            start = 0;
            while True:
                index = line.find(search,start);
                if index == -1:
                    break;
                print("line(%d)  \tindex(%d)\t%s" % (linen,index,sys_file_str))
                start = index+1
            linen +=1
            line = file.readline()
        file.close
    print "*"*70;

def replace_word(spec_dir,ignore_dir,spec_word,spec_replace_word,spec_type,spec_output):
    sys_file_arr = func(spec_dir,ignore_dir,spec_word,spec_type);
    file_path = conversion_spec_dir_path(spec_dir);
    file_output_path = conversion_spec_dir_path(spec_output);
    sys_file_repl_arr, spec_dir_repl = conversion_sys_file(sys_file_arr, file_path);
    sys_file_arr_len = len(sys_file_arr);
    
    for i in range(sys_file_arr_len):
        in_file = open(sys_file_arr[i],"r");
        out_file = open(sys_file_repl_arr[i],"w");

        for line in in_file:
            out_file.write(line.replace(spec_word,spec_replace_word));
        in_file.close();
        out_file.close();
    print "替换完成，以下为原文件的替换位置。\n替换后文件位置为 \"" + spec_dir_repl +"\"";
    find_word(spec_dir,ignore_dir,spec_word,spec_type);


def conversion_spec_dir_path(path):
    absolute_re="^/.*";
    relative_re="^(\./)|(\.\./).*";
    file_path = path;
    if re.search(absolute_re,path):
        pass;
    if re.search(relative_re,path):
        file_path = os.path.abspath(path);
    return file_path;

def conversion_sys_file(sys_file_arr, spec_dir, replace=".repl"):
    sys_file_repl_arr = [];
    spec_dir_repl = spec_dir+replace;
    for sys_file_str in sys_file_arr:
        sys_file_repl_arr.append(sys_file_str.replace(spec_dir, spec_dir_repl));
    for sys_file_repl_str in sys_file_repl_arr:
        if not os.path.exists(os.path.dirname(sys_file_repl_str)):
            os.makedirs(os.path.dirname(sys_file_repl_str));
        pass;
    return sys_file_repl_arr, spec_dir_repl;


def sys_argv():
    try:
        ignore_dir = [];
        spec_dir="";
        spec_word = "";
        spec_type = [];
        spec_replace_word = "";
        spec_output = "";

        opts, args = getopt.getopt(sys.argv[1:], "hi:d:f:r:t:", ["help", "ignore=", "dir==", "find==", "replace==", "type=="]);
        ignore_str = "";
        for name,value in opts:
            if name in ("-h", "--help"):
                usage();
                exit();
            if name in ("-f", "--find"):
                spec_word = value;
                spec_dir = "./";
                for i in range(len(opts)):
                    if "-d" in opts[i][0] or "--dir" in opts[i][0]:
                        spec_dir = conversion_spec_dir_path(opts[i][1]);
                    if "-i" in opts[i][0] or "--ignore" in opts[i][0]:
                        ignore_dir = opts[i][1].split(",");
                    if "-t" in opts[i][0] or "--type" in opts[i][0]:
                        spec_type = opts[i][1].split(",");
                    if "-r" in opts[i][0] or "--replace" in opts[i][0]:
                        spec_replace_word = opts[i][1];
        if spec_dir:
            if spec_replace_word is "":
                find_word(spec_dir,ignore_dir,spec_word,spec_type);
            else:
                replace_word(spec_dir,ignore_dir,spec_word,spec_replace_word,spec_type,spec_output);

    except getopt.GetoptError:
        pass; #ignore Parameter error!

def usage():
    print \
    """
            FINDWORD TOOLS v0.95
名称:
    findword.py     在指定文件夹下查找或替换所有文件中的指定内容。
描述：
    -f 或 --find==      指定find的单词，-f后指定一个单词
    -i 或 --ignore==    是忽略的文件夹名称，多项用逗号隔开
    -t 或 --type==      指定文件后缀，多项用逗号隔开
    -r 或 --replace==   指定替换的单词,使用此项后开启替换模式
举例:
    findword.py -f lucy -r lily -d ~/student -t php,html -i .git
    在~/student文件夹下的所有除了.git 的php,html文件中，查找和替换 lily为lucy
协议:
    GPL V3
作者:
    宸翰Hank
    """;

if __name__ == "__main__":
    sys_argv();
